package top.itlir.edc.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.itlir.edc.dao.MenuRepository;
import top.itlir.edc.dao.PermissionRepository;
import top.itlir.edc.dao.RoleRepository;
import top.itlir.edc.dao.UserRepository;
import top.itlir.edc.domain.Menu;
import top.itlir.edc.domain.Permission;
import top.itlir.edc.domain.Role;
import top.itlir.edc.domain.User;
import top.itlir.edc.service.IRoleService;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {

	@Resource
	private RoleRepository roleRepository;
	
	@Resource
	private MenuRepository menuRepository;
	
	@Resource
	private PermissionRepository permissionRepository;
	
	@Resource
	private UserRepository userRepository;

	@Override
	public Page<Role> findAll(Specification<Role> spec, Pageable pageable) {
		return roleRepository.findAll(spec, pageable);
	}

	@Override
	public void save(Role model, Integer[] permissions, String menuIds) {
		roleRepository.save(model);  
		
		// 角色关联菜单
		if (StringUtils.isNotBlank(menuIds)) {
			String[] idsArr = menuIds.split(",");
			for (String id : idsArr) {
				Menu menu = menuRepository.findOne(Integer.valueOf(id));
				model.getMenus().add(menu);
			}
		}
		
		// 角色关联权限
		if (null != permissions && permissions.length > 0) {
			for (Integer id : permissions) {
				Permission permission = permissionRepository.findOne(id);
				model.getPermissions().add(permission);
			}
		}
	}

	@Override
	public List<Role> findAll2() {
		return roleRepository.findAll();
	}

	@Override
	public List<Role> findRolesByUser(User user) {
		// 查询如果角色是admin就返回全部角色
		if ("admin".equals(user.getUsername())) {
			return roleRepository.findAll();
		} else {
			User user_role = userRepository.findOne(user.getId());
			Set<Role> roles = user_role.getRoles();
			List<Role> list = new ArrayList<Role>();
			if (null != roles && roles.size() > 0) {
					list.addAll(roles);
			}
			return list;
		}
	}

}
